<template>
    <div class="alarmConfiguration zy-content ">

      <div class="searchBox search-box-layout">
        <Row :gutter="24">
          <Col span="4">
            <div>
              <p class="label">{{$t('common.company')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.companyId" filterable clearable :placeholder="`${$t('common.selectInfo')}`"
                        @on-change="getBackupList(searchParams.companyId)">
                  <Option v-for="(item) of companyList" :value="item.id" :key="item.code"
                          :label="item.fullName">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.WarehouseNo')}}</p>
              <div class="ipt">
                <Select v-model="backupId" filterable clearable :placeholder="`${$t('common.selectInfo')}`"
                        @on-change="handleBackupSelect(backupId)" @on-open-change="openBackupSelect">
                  <Option v-for="(item) of backupList" :value="item.id" :key="item.id"
                          :label="item.backupNo+'-'+item.backupName">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('spareParts.ReservoirNo')}}</p>
              <div class="ipt">
                <Select v-model="shelfId" filterable clearable
                        :placeholder="`${$t('common.selectInfo')}`"
                        @on-change="handleShelfSelect(shelfId)" @on-open-change="openShelfSelect">
                  <Option v-for="(item) of shelfList" :value="item.id" :key="item.id" :label="item.shelfNo+'-'+item.shelf">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('spareParts.LocationNo')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.location" filterable clearable
                        :placeholder="`${$t('common.selectInfo')}`"
                        @on-open-change="openLocationSelect">
                  <Option v-for="(item) of locationList" :value="item.location" :key="item.id"
                          :label="item.locationNo+'-'+item.location">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" type="primary" v-if="checkBtnPermission.locationList" @click="changeNum()">{{$t('common.Query')}}</Button>
                <Button class="reset-btn" @click="reset()"
                        v-if="checkBtnPermission.locationList" >{{ $t('common.reset') }}
                </Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>
        <div class="list-layout mt16">
          <div class="btns clear">
            <!-- 批量删除 批量导出  批量导入 下载模板 新增-->

            <span class="title">{{ $t('common.listInformation') }}</span>
            <Button @click="createfaultCodeShowH" v-if="checkBtnPermission.locationAdd">{{$t('common.New')}}</Button>
            <Button @click="delFaultCodeShowClick" v-if="checkBtnPermission.locationDelete">{{$t('common.batchDelete')}}</Button>
            <Button @click="exportTemplateClick" v-if="checkBtnPermission.locationExport">{{$t('common.batchExport')}}</Button>
            <Button @click="importExcelShow" v-if="checkBtnPermission.locationImport">{{$t('common.Import')}}</Button>
            <Button  @click="exportTemplate" v-if="checkBtnPermission.locationTemplate">{{$t('common.Download')}}</Button>

            <Button @click="printShowClick">{{$t('选择打印')}}</Button>

              <Button @click="getTableColumns(columns)">
                  {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
              </Button>
          </div>
          <div class="tableContent">
            <Table class="resizable-table" border @on-column-width-resize="onColumnWidthResize"
                   :columns="columnsList" ellipsis ref="selection" stripe :data="dataArr"
                   @on-selection-change="onSelectChange">
              <template slot-scope="{ row }" slot="action">
                    <span class="operationBtn" @click="createfaultCodeShowH(row)"
                          v-if="checkBtnPermission.locationEdit"><i class="iconfont zy-common-bianji"></i>{{ $t('common.Edit') }}</span>
                <span class="operationBtn" @click="delPrrShowH(row)" v-if="checkBtnPermission.locationDelete"><i class="iconfont zy-common-shanchu"></i>{{$t('common.Delete')}}</span>
                <span class="operationBtn" v-has="'locationPrint'" @click="handlePrint(row)"><i class="iconfont zy-common-dayin"></i>{{ $t('打印') }}</span>
              </template>
            </Table>
          </div>
          <div class="pageWrap mt16">
            <pageLeftTitle :total="total" :selected="delIds.length" />
            <Page :total="total" :page-size="pageSize" :page-size-opts="pageSizeOption" :current="pageNum"
                  @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
          </div>
        </div>
        <Modal :mask-closable="false" v-model="create" :title="addtitle" @on-cancel="cancelModel()" class="modal-content-layout">
            <Form ref="form" class="formList" :model="formItem" label-position="top"
                :rules="ruleValidate">
                <!-- 公司 -->
                <FormItem :label="$t('common.company')"  prop="companyId">
                    <Select v-model="formItem.companyId" filterable
                            :placeholder="`${$t('common.selectInfo')}`"
                        @on-change="getBackupList(formItem.companyId)">
                        <Option v-for="(item) of companyList" :value="item.id" :key="item.code" :label="item.name">
                        </Option>
                    </Select>
                </FormItem>
                <!-- 仓库 -->
                <FormItem  :label="$t('spareParts.Warehouse')"  prop="backupConfigId">
                    <Select v-model="formItem.backupConfigId" filterable
                            :placeholder="`${$t('common.selectInfo')}`"
                        @on-change="getShelfList(formItem.backupConfigId)" @on-open-change="openBackupSelect">
                        <Option v-for="(item) of backupList" :value="item.id" :key="item.id" :label="item.backupNo+'-'+item.backupName">
                        </Option>
                    </Select>
                </FormItem>
                <!-- 货架 -->
                <FormItem   :label="$t('spareParts.Reservoir')"  prop="backupShelfConfigId">
                    <Select v-model="formItem.backupShelfConfigId" filterable
                            :placeholder="`${$t('common.selectInfo')}`"
                        @on-open-change="openShelfSelect">
                        <Option v-for="(item) of shelfList" :value="item.id" :key="item.id" :label="item.shelfNo+'-'+item.shelf">
                        </Option>
                    </Select>
                </FormItem>
                <!-- 库位 -->
                <FormItem  :label="$t('spareParts.LocationNo')"  prop="location">
                    <Input type="text" v-model="formItem.location" :placeholder="`${$t('common.inputInfo')}`" :maxlength="32"></Input>
                </FormItem>
                <FormItem  :label="$t('spareParts.LocationName')"  prop="locationNo">
                    <Input type="text" v-model="formItem.locationNo" :placeholder="`${$t('common.inputInfo')}`" :maxlength="32"></Input>
                </FormItem>
                <!-- 是否为报废库位 -->
                <FormItem  :label="$t('spareParts.ScrapLocation')"  prop="scrapStatus">
                    <RadioGroup v-model="formItem.scrapStatus">
                        <Radio v-for="item in types" :key="item.id" :label="item.id">{{ item.value }}</Radio>
                    </RadioGroup>
                </FormItem>
                <!-- 备注 -->
                <FormItem  :label="$t('common.remarks')" >
                    <Input type="textarea" v-model="formItem.remark" :placeholder="`${$t('common.inputInfo')}`"
                        :autosize="{ minRows: 2, maxRows: 5 }"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" :loading="loading" @click="addOk('form')">{{ $t('maintenance.Confirmed')
                }}</Button>
            </div>
        </Modal>
        <Modal :mask-closable="false" v-model="delFaultCodeShowF"   :title="$t('common.Delete')"
               class="modal-title-layout">
          <div class="icon red">
            <i class="iconfont zy-common-shanchu"></i>
          </div>
          <p class="title">
            <span>{{$t('common.confirmDelete')}}</span>
          </p>
            <div slot="footer">
                <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" :loading="loading" @click="deleteOk">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>
        <importExcelModal :importExcelStateF="importExcelState" v-if="importExcelState"
            @importExcelChange="importExcelChange"></importExcelModal>
      <ledgerPrintModal ref="ledgerPrintModal"/>
    </div>
</template>

<script>
import { searchApi, addApi, editApi, deleteApi, templateApi, exportApi } from "@/api/spareParts/location.js";
import { getUserSelect, getCompany, getBackup, getShelf, getLocation } from "@/api/index.js";
import importExcelModal from '@/components/importExcel.vue';
import fileDownload from 'js-file-download';
import ledgerPrintModal from './modules/ledgerPrintModal'
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
    name: "goodsShelves",//库位配置
    components: { importExcelModal,ledgerPrintModal },
    mixins:[toggleTableOperation],
    data() {
        return {
            companyList: [],
            backupList: [],
            shelfList: [],
            locationList: [],
            importExcelState: false, /*批量导入*/
            formItem: {},
            addtitle: "",
            allCheck: false,
            loading: false,
            create: false,
            searchParams: {},
            pageNum: 1,
            pageSize: 10,
            total: 0,
            dataArr: [],
            delFaultCodeShowF: false,//是否显示删除弹窗
            pageSizeOption: [10, 20, 30, 40],
            delIds: [],
            selection: [],
            checkBtnPermission: {},
            createByOptions: [],
            printArr:[],
            backupId: '',
            shelfId: '',
            types: [{ id: 0, value: '否' }, { id: 1, value: '是' }],
            columns: [
                {
                    key: 'selection',
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    //title: '公司',
                    title: `${ this.$t('common.company') }`,
                    key: 'companyName',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                   // title: `${this.$t('spareParts.Warehouse')}`,
                   title: `${ this.$t('common.WarehouseNo') }`,
                    key: 'backupName',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                   // title: `${this.$t('spareParts.Warehouse')}`,
                   title: `${ this.$t('common.Warehouse') }`,
                    key: 'backupNo',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                    //title: '货架',
                     title: `${ this.$t('spareParts.ReservoirNo') }`,
                    key: 'shelf',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                    //title: '货架',
                     title: `${ this.$t('spareParts.ReservoirName') }`,
                    key: 'shelfNo',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                    //title: `${this.$t('spareParts.Location')}`,
                     title: `${ this.$t('spareParts.LocationNo') }`,
                    key: 'location',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                    //title: `${this.$t('spareParts.Location')}`,
                     title: `${ this.$t('spareParts.LocationName') }`,
                    key: 'locationNo',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },

                {
                    //title: '是否为报废库位',
                    title: `${ this.$t('spareParts.ScrapLocation') }`,
                    key: 'scrapStatus',
                    minWidth: 150,
                    align: 'center',
                    render: (h, params) => {
                        return h('div', params.row.scrapStatus === 0 ? '否' : params.row.scrapStatus === 1 ? '是' : '')
                    },
                    resizable: true
                },
                {
                    //title: '管理员',
                     title: `${ this.$t('common.administrators') }`,
                    key: 'manageByName',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                   // title: '创建人',
                    title: `${ this.$t('common.CreateBy') }`,
                    key: 'createByName',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                    //title: '备注',
                    title: `${ this.$t('common.remarks') }`,
                    key: 'remark',
                    minWidth: 100,
                    align: 'center',
                    resizable: true
                },
                {
                   // title: '创建时间',
                   title: `${ this.$t('common.CreateTime') }`,
                    key: 'createTime',
                    minWidth: 200,
                    align: 'center',
                    resizable: true
                },
                {
                   //title: '操作',
                    title: `${this.$t('common.operation')}`,
                    slot: "action",
                    fixed: 'right',
                    minWidth: 250,
                    align: "center"
                }
            ],
            ruleValidate: {
                companyId: [
                    { required: true, message: '请选择公司', trigger: 'blur', type: "number" }
                ],
                backupConfigId: [
                    { required: true, message: '请选择仓库', trigger: 'blur', type: "number" }
                ],
                backupShelfConfigId: [
                    { required: true, message: '请选择货架', trigger: 'blur', type: "number" }
                ],
                location: [
                    { required: true, message: '请填写库位编号', trigger: 'blur'}
                ],
                locationNo: [
                    { required: true, message: '请填写库位名称', trigger: 'blur'}
                ],
                scrapStatus: [
                    { required: true, message: '请填写是否为报废库位', trigger: 'blur', type: "number" }
                ],
            }
        }
    },
    mounted() {

        this.getTableColumnsWidth(this.columns)

        this.searchList();
        this.getCompanyList();
        this.getUserList();
        let itemList = JSON.parse(window.localStorage.getItem('USER_URI'))
        for (let item of itemList) {
            if (item.code == "locationList") {
                this.checkBtnPermission.locationList = true
            }
            if (item.code == "locationAdd") {
                this.checkBtnPermission.locationAdd = true
            }
            if (item.code == "locationDelete") {
                this.checkBtnPermission.locationDelete = true
            }
            if (item.code == "locationEdit") {
                this.checkBtnPermission.locationEdit = true
            }
            if (item.code == "locationExport") {
                this.checkBtnPermission.locationExport = true
            }
            if (item.code == "locationImport") {
                this.checkBtnPermission.locationImport = true
            }
            if (item.code == "locationTemplate") {
                this.checkBtnPermission.locationTemplate = true
            }
        }

    },
    watch: {
        'searchParams.companyId': {
            handler(val, oldVal) {
                this.backupId = null
                this.shelfId = null
                this.$set(this.searchParams,'location',null)
                this.backupList = []
                this.shelfList = []
                this.locationList = []
            },
            deep: true
        },
        backupId: {
            handler(val, oldVal) {
                this.shelfId = null
                this.$set(this.searchParams,'location',null)
                this.shelfList = []
                this.locationList = []
            },
            deep: true
        },
        shelfId: {
            handler(val, oldVal) {
                this.$set(this.searchParams,'location',null)
                this.locationList = []
            },
            deep: true
        },

    },
    methods: {
      handlePrint(record){
        let arr = []
        arr.push(record)
        this.$refs.ledgerPrintModal.show(arr,1)
      },
      //批量打印
      printShowClick() {
            if (this.printArr.length == 0) {
                return;
            } else {
                this.$refs.ledgerPrintModal.show(this.printArr,1)
            }
        },
        //获取公司
        getCompanyList() {
            getCompany().then(res => {
                if (res.code === 200) {
                    this.companyList = res.data
                }
                else {
                    this.companyList = []
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
                this.loading = false
            })
        },
        //获取仓库
        async getBackupList(data) {
            this.$set(this.formItem,'backupConfigId',null)
            this.$set(this.formItem,'backupShelfConfigId',null)
            this.backupList = []
            this.shelfList = []
            this.locationList = []

            let params = {
                companyId: data
            }
            await getBackup(params).then(res => {
                if (res.code === 200) {
                    this.backupList = res.data
                }
                // else {
                //     this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                // }
            }).finally(() => {
                this.loading = false
            })
        },

        openBackupSelect(isOpen) {
            if (isOpen === true) {
                if (!this.searchParams.companyId && !this.formItem.companyId) {
                    this.$Message.warning(({ content: "请先选择公司", duration: 6, closable: true }));
                    return false;
                }
            }
        },
        //获取仓库名称
        handleBackupSelect(data) {
            if (!data) {
                this.searchParams.backupName = ""
            }
            this.backupList.map((item, index) => {
                if (item.id == data) {
                    this.searchParams.backupName = item.backupName
                }
            })
            this.getShelfList(data)
        },
        //获取货架下拉列表
        async getShelfList(data) {
            this.formItem.backupShelfConfigId = null
            this.shelfList = []
            this.locationList = []
            let params = {}
            params.delIds = []
            params.delIds.push(data)
            await getShelf(params).then(res => {
                if (res.code === 200) {
                    this.shelfList = res.data
                }
                else {
                    this.shelfList = []
                    //  this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
                this.loading = false
            })
        },
        openShelfSelect(isOpen) {
            if (isOpen === true) {
                if (!this.backupId && !this.formItem.backupConfigId) {
                    this.$Message.warning(({ content: "请先选择仓库", duration: 6, closable: true }));
                    return false;
                }
            }
        },
        //获取货架名称
        handleShelfSelect(data) {
            if (!data) {
                this.searchParams.shelf = ""
            }
            this.shelfList.map((item, index) => {
                if (item.id == data) {
                    this.searchParams.shelf = item.shelf
                }
            })
            this.getLocationList(data)
        },


        //获取库位下拉列表
        getLocationList(data) {
            let params = {}
            params.delIds = []
            params.delIds.push(data)
            getLocation(params).then(res => {
                if (res.code === 200) {
                    this.locationList = res.data
                }
                else {
                    this.locationList = []
                    // this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
                this.loading = false
            })
        },
        openLocationSelect(isOpen) {
            if (isOpen === true) {
                if (!this.searchParams.shelf && !this.formItem.shelf) {
                    this.$Message.warning(({ content: "请先选择货架", duration: 6, closable: true }));
                    return false;
                }
            }
        },

        //获取管理员
        getUserList() {
            getUserSelect().then(res => {
                if (res.code === 200) {
                    this.createByOptions = res.data.map(item => {
                        return {
                            ...item,
                            showName: item.empno + '----' + item.username
                        }
                    })
                } else {
                    this.createByOptions = []
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
                this.loading = false
            })
        },
      reset(){
        this.searchParams = {};
        this.changeNum();
      },
        //分页
        changeNum() {
            this.pageNum = 1;
            this.searchList();
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        //查询列表
        searchList() {
            let params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
            };
            for (let key in this.searchParams) {
                if (this.searchParams[key]) {
                    this.$set(params, key, this.searchParams[key])
                }
            }
            searchApi(params).then(res => {
                
                if (res.code === 200) {
                    this.dataArr = res.data.list
                    this.total = res.data.total
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        //增加或编辑
        createfaultCodeShowH(row) {
            this.$refs.form.resetFields();
            if (row.id) {
              this.formItem = {};
              this.backupList = [];
              this.shelfList = [];
              this.locationList = [];
              this.addtitle = `${this.$t('common.Edit')}`;
              if (row.companyId) {
                  this.getBackupList(row.companyId)
              }
              if (row.backupConfigId) {
                  this.getShelfList(row.backupConfigId)
              }
              this.formItem.id = row.id
              this.formItem.companyId = row.companyId
              this.formItem.backupConfigId = row.backupConfigId
              this.formItem.backupShelfConfigId = row.backupShelfConfigId
              this.formItem.scrapStatus = row.scrapStatus
              this.formItem.shelf = row.shelf
              this.formItem.remark = row.remark
              this.formItem.location = row.location
              this.formItem.locationNo = row.locationNo

            } else {
               this.addtitle = `${this.$t('common.New')}`
                this.formItem = {
                    companyId: null,
                    backupConfigId: null,
                    backupShelfConfigId: null,
                    location: null,
                    locationNo:null,
                    scrapStatus: null,
                };
                this.backupList= []
                this.shelfList= []
            }
            this.create = true;
        },
        cancelModel(){
             this.backupList= []
             this.shelfList= []
        },
        addOk(name) {
            this.$refs[name].validate((valid) => {
                if (!valid) {
                    return
                } else {
                    this.loading = true;
                    if (this.formItem.id) {
                        editApi(this.formItem).then(res => {
                            this.loading = false; 0
                            if (res.code === 200) {
                                this.changeNum();
                                this.$Message.success("编辑成功");
                                this.create = false;
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        })
                    } else {
                        addApi(this.formItem).then(res => {
                            this.loading = false;
                            if (res.code === 200) {
                                this.changeNum();
                                this.$Message.success("新增成功");
                                this.create = false;
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        })
                    }
                }
            })

        },
        //勾选列表
        onSelectChange(selection) {
            let myArray = [];
            let arr = []
            selection.map((item, index) => {
                myArray.push(item.id);
                arr.push(item)
            });
            this.delIds = myArray;
            this.printArr = arr
            if (selection.length > 0) {
                this.allCheck = true;
            } else {
                this.allCheck = false;
            }
        },
        //批量删除
        delFaultCodeShowClick() {
            if (this.delIds.length == 0) {
                this.$Message.warning({
                    content:`${ this.$t('common.deleteItems') }`,
                    duration: 6,
                    closable: true,
                });
                return;
            } else {
                this.delFaultCodeShowF = true;
            }
        },
        //删除
        delPrrShowH(row) {
            //点击展示提示删除弹窗
            this.delFaultCodeShowF = true;
            this.delIds = [];
            this.delIds.push(row.id);
        },
        deleteOk() {
            this.loading = true;
            let params = { delIds: this.delIds }
            deleteApi(params).then(res => {
                this.loading = false;
                if (res.code === 200) {
                    this.changeNum();
                    this.$Message.success("删除成功");
                    this.allCheck = false;
                    this.delFaultCodeShowF = false;
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        //下载模板
        exportTemplate() {
            const filName = '库位配置模板'
            templateApi().then(res => {
                fileDownload(res, filName + '.xlsx')
            })
        },
        //导入
        importExcelShow() {
            this.importExcelState = true;
        },
        importExcelChange(val) {
            this.importExcelState = false;
            if (val === 'success') {
                this.changeNum();
            }
        },
        //导出
        exportTemplateClick() {
            let params = {
                delIds: this.delIds,
            };
            for (let key in this.searchParams) {
                if (this.searchParams[key]) {
                    this.$set(params, key, this.searchParams[key])
                }
            }
            const filName = '库位配置'
            exportApi(params).then(res => {
                fileDownload(res, filName + '.xlsx')
            })
        }
    }
}
</script>

<style scoped lang="scss">
.ivu-input-number {
    width: -webkit-fill-available;
}
</style>



